package com.yuezhu.util;

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;

import com.baidu.location.LocationClient;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MyLocationConfiguration.LocationMode;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.map.PolylineOptions;
import com.baidu.mapapi.model.LatLng;
import com.yuezhu.global.ApplicationContext;

import java.util.ArrayList;
import java.util.List;

/**
 * 轨迹追踪
 */
@SuppressLint("NewApi")
public class BaiDuTrackUtil /*implements OnGetGeoCoderResultListener,
		BaiduMap.OnMapClickListener, OnGetRoutePlanResultListener,
		OnMarkerClickListener, OnGetPoiSearchResultListener,OnMapStatusChangeListener,OnMapDoubleClickListener*/ {
	private static BaiDuTrackUtil instance;
	private Context context;
	public BaiduMap mBaiduMap;

	/**
	 * 采集周期（单位 : 秒）
	 */
	private int gatherInterval = 5;

	/**
	 * 图标
	 */
	private static BitmapDescriptor realtimeBitmap;

	// 覆盖物
	public static OverlayOptions overlay;
	// 路线覆盖物
	private static PolylineOptions polyline = null;

	private static List<LatLng> pointList = new ArrayList<LatLng>();

	public boolean isTraceStart = false;


	public static MapStatusUpdate msUpdate = null;

	private View view = null;

	private LayoutInflater mInflater = null;

	public static boolean isInUploadFragment = true;
	private ArrayList<Marker> markerList=new ArrayList<Marker>();

	private BaiDuTrackUtil(BaiduMap mBaiduMap) {
		context = ApplicationContext.getContext();
		if(mBaiduMap!=null){
		    this.mBaiduMap = mBaiduMap;
	       /* this.mBaiduMap.setOnMapStatusChangeListener(this);
	        // 地图点击事件处理
	        this.mBaiduMap.setOnMapClickListener(this);
	        this.mBaiduMap.setOnMapDoubleClickListener(this); */
		}
	}

	public static BaiDuTrackUtil getInstance(BaiduMap mBaiduMap) {
		// if (instance == null) {
		instance = new BaiDuTrackUtil(mBaiduMap);
		// }
		return instance;
	}



	/**
	 * 添加地图覆盖物
	 */
	public void addMarker() {

		if (null != msUpdate) {
			mBaiduMap.setMapStatus(msUpdate);
		}

		// 路线覆盖物
		if (null != polyline) {
			mBaiduMap.addOverlay(polyline);
		}

		// 实时点覆盖物
		if (null != overlay) {
			mBaiduMap.addOverlay(overlay);
		}
	}

	private void showMessage(final String message, final Integer errorNo) {

		new Handler(context.getMainLooper()).post(new Runnable() {
			public void run() {
				if (null != errorNo) {
					if (0 == errorNo.intValue() || 10006 == errorNo.intValue()
							|| 10008 == errorNo.intValue()
							|| 10009 == errorNo.intValue()) {
					} else if (1 == errorNo.intValue()
							|| 10004 == errorNo.intValue()) {
					}
				}
			}
		});

	}

	private LocationMode mCurrentMode;
	private BitmapDescriptor mCurrentMarker;
	private boolean isFirstLoc = true; // 是否首次定位
	// 定位相关
	private LocationClient mLocClient;
//	public MyLocationListenner myListener = new MyLocationListenner();

	/**
	 * 百度定位
	 *//*
	public void baiduLocation() {
		// 开启定位图层
		mBaiduMap.setMyLocationEnabled(true);
		// 修改为自定义marker
		mCurrentMarker = BitmapDescriptorFactory
				.fromResource(R.drawable.umeng_socialize_location_ic);
		mBaiduMap.setMyLocationConfigeration(new MyLocationConfiguration(
				mCurrentMode, true, mCurrentMarker));
		// 定位初始化
		mLocClient = new LocationClient(context);
		mLocClient.registerLocationListener(myListener);
		LocationClientOption option = new LocationClientOption();
		option.setOpenGps(true); // 打开gps
		option.setCoorType("bd09ll"); // 设置坐标类型
		option.setScanSpan(1000);
		mLocClient.setLocOption(option);
		mLocClient.start();
	}

	*//**
	 * 定位SDK监听函数
	 *//*
	public class MyLocationListenner implements BDLocationListener {

		@Override
		public void onReceiveLocation(BDLocation location) {

			MyLocationData locData = new MyLocationData.Builder()
					// 此处设置开发者获取到的方向信息，顺时针0-360
					.latitude(location.getLatitude())
					.longitude(location.getLongitude()).build();
			mBaiduMap.setMyLocationData(locData);
			if (isFirstLoc) {
				// isFirstLoc = false;
				// mLocClient.stop();
				LatLng ll = new LatLng(location.getLatitude(),
						location.getLongitude());
				MapStatus.Builder builder = new MapStatus.Builder();
				builder.target(ll).zoom(18.0f);
				mBaiduMap.animateMapStatus(MapStatusUpdateFactory
						.newMapStatus(builder.build()));
			}
		}

		public void onReceivePoi(BDLocation poiLocation) {
		}
	}

	// ---------------------车辆追踪相关


	*//**
	 * entity标识
	 *//*
	public static String entityName = null;

	*//**
	 * 鹰眼服务ID，开发者创建的鹰眼服务对应的服务ID
	 *//*
	public static long serviceId = 112266; // serviceId为开发者创建的鹰眼服务ID

	*//**
	 * 轨迹服务类型（0 : 不建立socket长连接， 1 : 建立socket长连接但不上传位置数据，2 : 建立socket长连接并上传位置数据）
	 *//*
	private int traceType = 2;



	*//**
	 * 获取设备IMEI码
	 * 
	 * @param context
	 * @return
	 *//*
	protected static String getImei(Context context) {
		String mImei = "NULL";
		try {
			mImei = ((TelephonyManager) context
					.getSystemService(Context.TELEPHONY_SERVICE)).getDeviceId();
		} catch (Exception e) {
			System.out.println("获取IMEI码失败");
			mImei = "NULL";
		}
		return mImei;
	}


	// 获取地图中心点坐标
	*//**
	 * 地图状态改变
	 *//*
	public void baiduCenterLocation() {
		mBaiduMap.setOnMapStatusChangeListener(new OnMapStatusChangeListener() {
			@Override
			public void onMapStatusChangeStart(MapStatus status) {
				updateMapState(status);
			}

			@Override
			public void onMapStatusChangeFinish(MapStatus status) {
				updateMapState(status);
			}

			@Override
			public void onMapStatusChange(MapStatus status) {
				updateMapState(status);
			}
		});
	}

	// 获取地图中心点位置
	private void updateMapState(MapStatus status) {
		LatLng mCenterLatLng = status.target;
		*//** 获取经纬度 *//*
		double lat = mCenterLatLng.latitude;
		double lng = mCenterLatLng.longitude;
		mSearch.reverseGeoCode(new ReverseGeoCodeOption()
				.location(mCenterLatLng));
	}

	// 地理编码反地理编码
	private GeoCoder mSearch = null; // 搜索模块，也可去掉地图模块独立使用

	private void initGeoRes() {
		mSearch = GeoCoder.newInstance();
		mSearch.setOnGetGeoCodeResultListener(this);
	}

	@Override
	public void onGetGeoCodeResult(GeoCodeResult result) {
		LogUtils.e("result", result+" 地理编码");
		if (result == null || result.error != SearchResult.ERRORNO.NO_ERROR) {
			Toast.makeText(context, "抱歉，未能找到结果", Toast.LENGTH_LONG).show();
			return;
		}
		String strInfo = String.format("纬度：%f 经度：%f",
				result.getLocation().latitude, result.getLocation().longitude);
		LogUtils.e("location", result.getLocation() + "");
		addMarks(result.getLocation(),emPlace);
	}

	@Override
	public void onGetReverseGeoCodeResult(ReverseGeoCodeResult result) {
		if (result == null || result.error != SearchResult.ERRORNO.NO_ERROR) {
			Toast.makeText(context, "抱歉，未能找到结果", Toast.LENGTH_LONG).show();
			return;
		}

		Toast.makeText(context, result.getAddress(), Toast.LENGTH_LONG).show();

	}

	// -------------------------百度地图路线搜索
	*//**
	 * 此activity用来展示如何进行驾车路线搜索并在地图使用RouteOverlay、TransitOverlay绘制
	 * 同时展示如何进行节点浏览并弹出泡泡
	 *//*
	int nodeIndex = -1; // 节点索引,供浏览节点时使用
	RouteLine route = null;
	OverlayManager routeOverlay = null;
	boolean useDefaultIcon = false;
	private TextView popupText = null; // 泡泡view
	// 搜索相关
	RoutePlanSearch routeSearch = null; // 搜索模块，也可去掉地图模块独立使用

	public void aboutRout() {
		// 地图点击事件处理
		mBaiduMap.setOnMapClickListener(this);
		mBaiduMap.setOnMapDoubleClickListener(this);
		mBaiduMap.setOnMarkerClickListener(this);
		// 初始化搜索模块，注册事件监听
		routeSearch = RoutePlanSearch.newInstance();
		routeSearch.setOnGetRoutePlanResultListener(this);
		// 设置起终点信息，对于tranist search 来说，城市名无意义
		PlanNode stNode = PlanNode.withCityNameAndPlaceName("北京", "奥林匹克公园");
		PlanNode enNode = PlanNode.withCityNameAndPlaceName("北京", "国贸");
		routeSearch.drivingSearch((new DrivingRoutePlanOption()).from(stNode)
				.to(enNode));
	}

	@Override
	public void onGetTransitRouteResult(TransitRouteResult result) {

	}
	@Override
	public void onGetWalkingRouteResult(WalkingRouteResult arg0) {
		// TODO Auto-generated method stub
	}

	@Override
	public void onGetDrivingRouteResult(DrivingRouteResult result) {

		if (result == null || result.error != SearchResult.ERRORNO.NO_ERROR) {
			Toast.makeText(context, "抱歉，未找到结果", Toast.LENGTH_SHORT).show();
		}
		if (result.error == SearchResult.ERRORNO.AMBIGUOUS_ROURE_ADDR) {
			// 起终点或途经点地址有岐义，通过以下接口获取建议查询信息
			// result.getSuggestAddrInfo()
			return;
		}
		if (result.error == SearchResult.ERRORNO.NO_ERROR) {
			nodeIndex = -1;
			route = result.getRouteLines().get(0);
			DrivingRouteOverlay overlay = new MyDrivingRouteOverlay(mBaiduMap);
			mBaiduMap.setOnMarkerClickListener(overlay);
			routeOverlay = overlay;
			overlay.setData(result.getRouteLines().get(0));
			overlay.addToMap();
			overlay.zoomToSpan();
		}

	}

	private void addMarks(LatLng point, Place emPlace1) {
		*//*
		 * BitmapDescriptor descriptor = BitmapDescriptorFactory
		 * .fromResource(R.drawable.me_red_point);
		 *//*
		RelativeLayout location = (RelativeLayout) LayoutInflater.from(context)
				.inflate(R.layout.marklayout, null);
		TextView contentView = (TextView) location
				.findViewById(R.id.markcontent);
		contentView.setPadding(10, 2, 20, 10);
		ImageView start_end_Image = (ImageView) location
				.findViewById(R.id.map_start_end);
		start_end_Image.setVisibility(View.VISIBLE);
		contentView.setVisibility(View.GONE);
		RelativeLayout.LayoutParams params = (LayoutParams) start_end_Image
				.getLayoutParams();
		int width = ApplicationContext.getInstance().getScreen_width();
		params.width = width / 10;
		params.height = width / 10;
		switch (emPlace1) {
		case START_PLACE:
			start_end_Image.setImageResource(R.drawable.icon_st);
			screen_Mark(point, location, Place.START_PLACE);
			emPlace = Place.END_PLACE;
			mSearch.geocode(new GeoCodeOption().city(end_city).address(
					end_address));
			break;
		case END_PLACE:
			start_end_Image.setImageResource(R.drawable.icon_en);
			screen_Mark(point, location, Place.END_PLACE);
//			emPlace = Place.MIDDLE_PLACE;
			*//*
			 * mSearch.geocode(new GeoCodeOption().city("北京").address( "国贸"));
			 *//*
			
			break;
		case MIDDLE_PLACE:
			contentView.setVisibility(View.VISIBLE);
			start_end_Image.setVisibility(View.GONE);
			
			if (middle_index <= carTracList.size() - 1) {
				CarTracBeen entity = carTracList.get(middle_index);
				contentView.setText(entity.getLicence_plate());
				screen_Mark(point, location, Place.MIDDLE_PLACE);
				++middle_index;
				if (middle_index < carTracList.size()) {
					LatLng ptCenter = new LatLng((Float.valueOf(carTracList
							.get(middle_index).getLatitude())),
							(Float.valueOf(carTracList.get(middle_index)
									.getLongitude())));
					addMarks(ptCenter, Place.MIDDLE_PLACE);
				}

			}
			break;
		default:
			break;
		}
	}
private LatLng last_point;
	private void screen_Mark(LatLng point, RelativeLayout location, Place emPlace1) {
		BitmapDescriptor descriptor = BitmapDescriptorFactory
				.fromView(location);
		OverlayOptions options = new MarkerOptions().position(point)
				.icon(descriptor).zIndex(5);
		LogUtils.e("baidu", mBaiduMap + "");
		Marker marker = (Marker) mBaiduMap.addOverlay(options);
		markerList.add(marker);
		// 为marker添加识别标记信息
		Bundle bundle = new Bundle();
		bundle.putSerializable("info", "辽 DF67");
		marker.setExtraInfo(bundle); // 将地图移到到最后一个经纬度位置
		float f = mBaiduMap.getMaxZoomLevel();// 19.0
		float m = mBaiduMap.getMinZoomLevel();// 3.0
		MapStatusUpdate u = MapStatusUpdateFactory.newLatLngZoom(point,6);
		if (emPlace1 == Place.MIDDLE_PLACE) {
			last_point = point;
			mBaiduMap.setMapStatus(u);
		}
	}

	private class MyDrivingRouteOverlay extends DrivingRouteOverlay {

		public MyDrivingRouteOverlay(BaiduMap baiduMap) {
			super(baiduMap);
		}

		@Override
		public BitmapDescriptor getStartMarker() {
			if (useDefaultIcon) {
				return BitmapDescriptorFactory.fromResource(R.drawable.icon_st);
			}
			return null;
		}

		@Override
		public BitmapDescriptor getTerminalMarker() {
			if (useDefaultIcon) {
				return BitmapDescriptorFactory.fromResource(R.drawable.icon_en);
			}
			return null;
		}
	}

	@Override
	public boolean onMarkerClick(Marker marker) {
		*//*
		 * // TODO Auto-generated method stub // 获得marker中的数据 String info =
		 * (String) marker.getExtraInfo().get("info"); //
		 * 生成一个TextView用户在地图中显示InfoWindow LinearLayout location = (LinearLayout)
		 * LayoutInflater.from(context).inflate(R.layout.marklayout,null);
		 * TextView contentView = (TextView)
		 * location.findViewById(R.id.markcontent); contentView.setPadding(10,
		 * 2, 20, 10); contentView.setText(info); // 将marker所在的经纬度的信息转化成屏幕上的坐标
		 * final LatLng ll = marker.getPosition(); Point p =
		 * mBaiduMap.getProjection().toScreenLocation(ll); LatLng llInfo =
		 * mBaiduMap.getProjection().fromScreenLocation(p); //
		 * 为弹出的InfoWindow添加点击事件 InfoWindow mInfoWindow = new
		 * InfoWindow(BitmapDescriptorFactory.fromView(location), llInfo, 1,new
		 * OnInfoWindowClickListener() {
		 * 
		 * @Override public void onInfoWindowClick() { // TODO Auto-generated
		 * method stub // mBaiduMap.hideInfoWindow(); } }); // 显示最后一条的InfoWindow
		 * // mBaiduMap.showInfoWindow(mInfoWindow);
		 *//*return true;
	}

	// --------业务代码 车辆追踪界面
	private String start_address, start_city, end_address, end_city;
	private List<CarTracBeen> carTracList;

	enum Place {
		START_PLACE, END_PLACE, MIDDLE_PLACE
	}

	private Place emPlace = Place.START_PLACE;
	private int middle_index = 0;

	public void VehicleTrack(String start_address, String start_city,
							 String end_address, String end_city, List<CarTracBeen> carTracList) {
		this.start_address = start_address;
		this.start_city = start_city;
		this.end_address = end_address;
		this.end_city = end_city;
		LogUtils.e("起点终点", start_address+" start_address    start_city "+start_city+"  "+end_address+" end_address  ecity "+end_city);
		this.carTracList = getCarTracList(carTracList);
		mSearch.geocode(new GeoCodeOption().city(start_city).address(
				start_address));
		if (carTracList.size() > 0) {
			LatLng ptCenter = new LatLng((Float.valueOf(carTracList.get(0)
					.getLatitude())), (Float.valueOf(carTracList.get(0)
					.getLongitude())));
			addMarks(ptCenter, Place.MIDDLE_PLACE);
		}
	}

	private List<CarTracBeen> getCarTracList(List<CarTracBeen> carTracList) {
		List<CarTracBeen> list = new ArrayList<CarTracBeen>();
		for (int i = 0; i < carTracList.size(); i++) {
			*//*carTracList.get(i).setLatitude("39.919462222222");
			carTracList.get(i).setLongitude("116.44724444444");*//*
			if (!StringUtil.isEmpty(carTracList.get(i).getLatitude())) {
				list.add(carTracList.get(i));
			}
		}
		return list;
	}
private boolean carManager = false ;
	// 车辆管理显示车辆位置

	public ArrayList<Marker> addCarManagerMarks(List<CarTracBeen> carTracList1) {
		carManager = true ;
		this.carTracList = getCarTracList(carTracList1);
		markerList.clear();
		LogUtils.e("carTracList----"+this.carTracList.toString());
		if (carTracList.size() > 0) {
			emPlace = Place.MIDDLE_PLACE;
			CarTracBeen carTracBeen = carTracList.get(0);
			double latitude = Double.parseDouble(carTracBeen.getLatitude());
			double longitude = Double.parseDouble(carTracBeen.getLongitude());
			LatLng point = new LatLng(latitude, longitude);
			addMarks(point,emPlace);
		}
		return markerList;
	}

	// 跳转到百度地图
	public void jumpBaiduMapApp(Context context, LatLng start, LatLng end,
								String city, String name) {
		Intent intent;
		double s_latitude = start.latitude;
		double s_longitude = start.longitude;
		double e_latitude = end.latitude;
		double e_longitude = end.longitude;
		try {
			intent = Intent
					.getIntent("intent://map/direction?origin=latlng:"
							+ s_latitude
							+ ","
							+ s_longitude
							+ "|name:我"
							+ "&destination=latlng:"
							+ e_latitude
							+ ","
							+ e_longitude
							+ "|name:"
							+ name
							+ "&mode=walking&region="
							+ city
							+ "&src=yourCompanyName|危运宝#Intent;scheme=bdapp;package=com.baidu.BaiduMap;end");
			if (intent.resolveActivity(context.getPackageManager()) != null) {
				context.startActivity(intent);
			} else {
				MyToast.showDefaltToast("您的手机没有安装百度地图");
			}
		} catch (URISyntaxException e) {
			e.printStackTrace();
		}
	}

	// 跳转到高德地图
	public void jumpGaoDeMapApp(Context context, LatLng location) {
		double s_latitude = location.latitude;
		double s_longitude = location.longitude;
		Intent gaodeIntent = new Intent(
				"android.intent.action.VIEW",
				android.net.Uri
						.parse("androidamap://showTraffic?sourceApplication=softname&poiid=BGVIS1&lat="
								+ gps.getWgLat()
								+ "&lon="
								+ gps.getWgLon()
								+ "&level=18&dev=0"));
		gaodeIntent.setPackage("com.autonavi.minimap");
		if (gaodeIntent.resolveActivity(context.getPackageManager()) != null) {
			context.startActivity(gaodeIntent);
		} else {

			MyToast.showDefaltToast("您的手机没有安装高德地图，高德地图的版本需要高于V4.1.3");
		}
	}

	// 搜索附近POI
	public void searchPoiNear(LatLng ptCenter, String keyWord, int radius,
							  int pageNum) {
		PoiSearch poiSearch = PoiSearch.newInstance();
		poiSearch.searchNearby((new PoiNearbySearchOption()).location(ptCenter)
				.keyword(keyWord).radius(radius).pageNum(pageNum)
				.sortType(PoiSortType.distance_from_near_to_far));
		poiSearch.setOnGetPoiSearchResultListener(this);
	}

	@Override
	public void onGetPoiDetailResult(PoiDetailResult arg0) {

	}

	@Override
	public void onGetPoiResult(PoiResult result) {
		if (sPoiNearListener != null) {
			sPoiNearListener.getPoiResult(result);
		}
	}

	public interface searchPoiNearListener {
		void getPoiResult(PoiResult result);
	}

	// 搜索附近兴趣点结果监听
	private static searchPoiNearListener sPoiNearListener = null;

	public void setSearchPoiNearListener(searchPoiNearListener sPoiNearListener) {
		this.sPoiNearListener = sPoiNearListener;
	}

	@Override
	public void onMapStatusChange(MapStatus arg0) {
		// TODO Auto-generated method stub
	}

	@Override
	public void onMapStatusChangeFinish(MapStatus arg0) {
		// TODO Auto-generated method stub
		if (!carManager) {
			MapStatusUpdate u = MapStatusUpdateFactory.newLatLngZoom(last_point,arg0.zoom);
			mBaiduMap.setMapStatus(u);
		}
		
	}

	@Override
	public void onMapStatusChangeStart(MapStatus arg0) {
		// TODO Auto-generated method stub
		
	}
	private float lastZoom  = 6;
	private int clickCount = 1 ;
	@Override
	public void onMapDoubleClick(LatLng arg0) {
		// TODO Auto-generated method stub
		if (!carManager) {
		++clickCount;
		LogUtils.e("双击", clickCount+"    "+clickCount*lastZoom);
		MapStatusUpdate u = MapStatusUpdateFactory.newLatLngZoom(last_point,lastZoom*clickCount);
		mBaiduMap.setMapStatus(u);
		}
	}
	@Override
	public void onMapClick(LatLng point) {
		if (!carManager) {
		++clickCount;
		LogUtils.e("单击", clickCount+"    "+clickCount*lastZoom);
		MapStatusUpdate u = MapStatusUpdateFactory.newLatLngZoom(last_point,lastZoom*clickCount);
		mBaiduMap.setMapStatus(u);
		}
	}

	@Override
	public boolean onMapPoiClick(MapPoi poi) {
		return false;
	}*/
}
